package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JSONResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    //查询部门请求
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo){

        PageResult<Permission> pageResult = permissionService.query(qo);
        model.addAttribute("pageResult", pageResult);

        List<Permission> permissions = permissionService.listALL();
        model.addAttribute("permissions", permissions);

        model.addAttribute("departments", departmentService.listALL());
        return "permission/list";
    }
    //处理删除部门请求
    @RequestMapping("/delete")
    @ResponseBody
    public JSONResult delete(Long id){

        try {

            permissionService.delete(id);
            return new JSONResult();

        } catch(Exception e) {
            e.printStackTrace();

            return new JSONResult(false,"警告");
        }
    }

    //处理新增部门信息
    @RequestMapping("/input")
    public String input(Long id,Model model){

        List<Department> departments = departmentService.listALL();
        model.addAttribute("departments", departments);

        model.addAttribute("roles", roleService.listALL());
        if (id != null) {
            Permission permission = permissionService.get(id);
            model.addAttribute("permission", permission);

        }

        return "permission/list";
    }

    //处理新增和修改页面
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Permission permission,Long[] ids){

        if (permission.getId() != null) {

            permissionService.update(permission,ids);
        }else {
            permissionService.save(permission,ids);

        }
        return "redirect:/permission/list.do";
    }

    @RequestMapping("/reload")
    @ResponseBody
    public JSONResult reload(){


         try {

             permissionService.reload();
             return new JSONResult();
         } catch(Exception e) {
             e.printStackTrace();

             return new JSONResult(false,"加载失败!");
         }
    }
}
